/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable no-console */
/* eslint-disable no-plusplus */
/* eslint-disable @typescript-eslint/no-non-null-asserted-optional-chain */
import React, { useState } from 'react';
import { Button, Card, Form, message, Spin } from 'antd';
import ProForm, {
  ModalForm,
  ProFormDigit,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-form';
import { EditOutlined } from '@ant-design/icons';
import type { CurrentUser } from 'umi';
import { connect } from 'umi';
import type { ConnectState } from '@/models/connect';
import type {
  GetSellerInfoParamsType,
  EditSellerParamsType} from '@/services/seller';
import {
  getSellerInfo,
  editSeller
} from '@/services/seller';
import MapForm from './MapForm';
import styles from './UpdateForm.less';

interface UpdateFormProps {
  sellerId: string; // 商家编号
  userState?: CurrentUser;
  updateFormShow?: Function; // 显示弹窗事件
  updateEvent?: Function; // 更新事件
}

const leasingMode = [
  {
    label: '押金',
    value: 1,
  },
  {
    label: '免押',
    value: 2,
  },
  {
    label: '押金+免押',
    value: 3,
  },
];

const UpdateFrom: React.FC<UpdateFormProps> = (props) => {
  const { sellerId, userState, updateFormShow, updateEvent } = props;
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [search, setSearch] = useState(false);
  const [sellerData, setSellerData] = useState({
    phone: '',
    name: '',
    addr: '',
    latitude: '',
    longitude: '',
    rate_mode: 1,
    wx_leasing_mode: 1,
    wx_pb_leasing_mode: 1,
    zfb_leasing_mode: 1,
    zfb_pb_leasing_mode: 1,
    billingtime: 0,
    billingunit: 1,
    amount: '',
    freetime: '',
    ceiling: '',
    deposit: '',
    pl_mode_1: '',
    pl_mode_2: '',
    pl_mode_3: '',
    pl_mode_4: '',
    pl_mode_5: '',
    pl_mode_6: '',
    pl_mode_7: '',
    pl_mode_8: '',
    pl_mode_9: '',
    pl_mode_10: '',
    pl_mode_11: '',
    pl_mode_12: '',
    pl_mode_13: '',
    wired_deposit: '',
    wired_pay_score_start_unit: '',
    wired_pay_score_start_type: 1,
    wired_pay_score_start_amount: '',
    wired_pay_score_unit: '',
    wired_pay_score_type: 1,
    wired_pay_score_amount: '',
  });

  // 获取商家信息
  const getSellerData = async () => {
    // 获取商家信息
    const data: GetSellerInfoParamsType = {
      uId: userState?.id!,
      userType: userState?.user_type!,
      token: userState?.token!,
      sId: sellerId,
    };
    setLoading(true);

    try {
      const res = await getSellerInfo(data);
      if (res.code === 0) {
        console.log(res.data);
        const resData = res.data;
        const plModeArr = resData.wired_amount.split(':');
        const plStartMode = resData.wired_pay_score_start_amount.split('|');
        const plMode = resData.wired_pay_score_amount.split('|');
        const newSellerData = {
          phone: resData.phone,
          name: resData.name,
          addr: resData.addr,
          longitude: resData.longitude,
          latitude: resData.latitude,
          rate_mode: resData.rate_mode,
          wx_leasing_mode: resData.wx_leasing_mode,
          wx_pb_leasing_mode: resData.wx_pb_leasing_mode,
          zfb_leasing_mode: resData.zfb_leasing_mode,
          zfb_pb_leasing_mode: resData.zfb_pb_leasing_mode,
          billingtime: resData.billingtime,
          billingunit: resData.billingunit,
          amount: resData.amount,
          freetime: resData.freetime,
          deposit: resData.deposit,
          ceiling: resData.ceiling,
          pl_mode_1: plModeArr[0],
          pl_mode_2: plModeArr[1],
          pl_mode_3: plModeArr[2],
          pl_mode_4: plModeArr[3],
          pl_mode_5: plModeArr[4],
          pl_mode_6: plModeArr[5],
          pl_mode_7: plModeArr[6],
          pl_mode_8: plModeArr[7],
          pl_mode_9: plModeArr[8],
          pl_mode_10: plModeArr[9],
          pl_mode_11: plModeArr[10],
          pl_mode_12: plModeArr[11],
          pl_mode_13: plModeArr[12],
          wired_deposit: resData.wired_deposit,
          wired_pay_score_start_unit: plStartMode[0],
          wired_pay_score_start_type: plStartMode[1],
          wired_pay_score_start_amount: plStartMode[2],
          wired_pay_score_unit: plMode[0],
          wired_pay_score_type: plMode[1],
          wired_pay_score_amount: plMode[2],
        };
        setSellerData(newSellerData);
        // 设置表格默认值
        form.setFieldsValue(newSellerData);
      }
    } catch (err) {
      message.error('加载失败,请重试!');
    }

    setLoading(false);
  };
  // 修改商家信息
  const editSellerData = async (values: typeof sellerData) => {
    // 处理充电线套餐
    let pl = '';
    for (let i = 1; i <= 13; i++) {
      if (values[`pl_mode_${  i}`]) {
        pl += values[`pl_mode_${  i}`];
      }
      if (i !== 13) {
        pl += ':';
      }
    }
    const pl_start_rule =
      `${values.wired_pay_score_start_unit 
      }|${ 
      values.wired_pay_score_start_type 
      }|${ 
      values.wired_pay_score_start_amount}`;
    const pl_rule =
      `${values.wired_pay_score_unit 
      }|${ 
      values.wired_pay_score_type 
      }|${ 
      values.wired_pay_score_amount}`;

    const data: EditSellerParamsType = {
      uId: userState?.id!,
      userType: userState?.user_type!,
      token: userState?.token!,
      sId: sellerId,
      name: values.name,
      longitude: values.longitude,
      latitude: values.latitude,
      rate_mode: values.rate_mode,
      wx_leasing_mode: values.wx_leasing_mode,
      wx_pb_leasing_mode: values.wx_pb_leasing_mode,
      zfb_leasing_mode: values.zfb_leasing_mode,
      zfb_pb_leasing_mode: values.zfb_pb_leasing_mode,
      billingtime: values.billingtime,
      billingunit: values.billingunit,
      amount: values.amount,
      freetime: values.freetime,
      deposit: values.deposit,
      ceiling: values.ceiling,
      wired_deposit: values.wired_deposit,
      wired_amount: pl,
      wired_pay_score_start_amount: pl_start_rule,
      wired_pay_score_amount: pl_rule,
    };

    try {
      const res = await editSeller(data);
      if (res.code === 0) {
        setTimeout(() => {
          message.success('更新成功!');
        }, 300);
        if (updateEvent) updateEvent();
        return true;
      } 
        return false;
      
    } catch (err) {
      console.log(err);
      return false;
    }
  };

  // 修改商家经纬度
  const setFormLocation = (lng: string, lat: string, name: string) => {
    form.setFieldsValue({
      longitude: lng,
      latitude: lat,
      addr: name,
    });
    setSellerData((currentData) => {
      const nowData = {
        ...currentData,
      };
      nowData.longitude = lng;
      nowData.latitude = lat;
      nowData.addr = name;
      return nowData;
    });
  };
  return (
    <ModalForm
      title="修改商户"
      form={form}
      trigger={
        <Button type="primary">
          <EditOutlined />
          修改
        </Button>
      }
      modalProps={{
          okText: '更新'
      }}
      onVisibleChange={async (show) => {
        if (updateFormShow) updateFormShow(show);
        if (show) {
          await getSellerData();
        }
      }}
      onFinish={async (values) => {
        return await editSellerData(values as any);
      }}
    >
      <Spin spinning={loading} key={sellerId}>
        <Card className={styles.Card} title="基本信息">
          <ProForm.Group>
            <ProFormText
              name="name"
              width="md"
              label="商户名称"
              placeholder="请输入商户名称"
              rules={[{ required: true }]}
            />
            <ProFormText
              name="phone"
              width="md"
              label="负责人手机"
              placeholder="请输入负责人手机"
              disabled
              rules={[{ required: true }]}
            />
          </ProForm.Group>
          {/* 密码 */}
          <ProFormText.Password
            name="password"
            width="lg"
            label="登录密码"
            placeholder="请输入登录密码"
          />
          <ProForm.Group>
            {/* 商户地址 */}
            <ProFormText
              name="addr"
              width="lg"
              label="商户地址"
              placeholder="请输入商户地址"
              rules={[{ required: true }]}
            />
            <Button onClick={() => (search ? setSearch(false) : setSearch(true))}>
              获取经纬度
            </Button>
          </ProForm.Group>
          {search && (
            <MapForm
              lat={sellerData.latitude}
              lng={sellerData.longitude}
              setLocation={(lng: string, lat: string, name: string) =>
                setFormLocation(lng, lat, name)
              }
            ></MapForm>
          )}
          {/* 经纬度 */}
          <ProForm.Group>
            <ProFormText name="longitude" width="md" label="商户经度" placeholder="请输入商户经度" />
            <ProFormText name="latitude" width="md" label="商户纬度" placeholder="请输入商户纬度" />
          </ProForm.Group>
        </Card>
        {/* <Card title="分润模式">
          <ProFormRadio.Group
            name="rate_mode"
            label="分润模式"
            options={
              sellerData.rate_mode == 1
                ? [
                    {
                      label: '绝对分润',
                      value: 1,
                    },
                  ]
                : [
                    {
                      label: '相对分润',
                      value: 2,
                    },
                  ]
            }
          />
          <ProFormSlider
            name="slider"
            label="商户"
            marks={{
              0: 'A',
              20: 'B',
              40: 'C',
              60: 'D',
              80: 'E',
              100: 'F',
            }}
          />
        </Card> */}
        <Card className={styles.Card} title="租借模式">
          <ProFormRadio.Group name="wx_leasing_mode" label="微信充电线" options={leasingMode} />
          <ProFormRadio.Group name="wx_pb_leasing_mode" label="微信充电宝" options={leasingMode} />
          <ProFormRadio.Group name="zfb_leasing_mode" label="支付宝充电线" options={leasingMode} />
          <ProFormRadio.Group
            name="zfb_pb_leasing_mode"
            label="支付宝充电宝"
            options={leasingMode}
          />
        </Card>
        <Card className={styles.Card} title="充电宝计费方式">
          <ProFormRadio.Group
            name="billingunit"
            label="计费模式"
            options={[
              {
                label: '小时计费',
                value: 1,
              },
              {
                label: '分钟计费',
                value: 2,
              },
            ]}
          />
          <ProForm.Group>
            <ProFormText
              name="billingtime"
              width="md"
              label="计费时间"
              placeholder="请输入计费时间"
              fieldProps={{
                addonBefore: '每',
                addonAfter: sellerData.billingunit === 1 ? '小时' : '分钟',
              }}
              rules={[{ required: true }]}
            />
            <ProFormText
              name="amount"
              width="md"
              label="计费单价"
              placeholder="请输入计费单价"
              fieldProps={{
                addonBefore: '收费',
                addonAfter: '¥',
              }}
              rules={[{ required: true }]}
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormText
              name="ceiling"
              width="md"
              label="每日封顶值"
              placeholder="请输入每日封顶值"
              fieldProps={{
                addonAfter: '¥',
              }}
              rules={[{ required: true }]}
            />
            <ProFormText
              name="deposit"
              width="md"
              label="押金"
              placeholder="请输入押金"
              fieldProps={{
                addonAfter: '¥',
              }}
              rules={[{ required: true }]}
            />
          </ProForm.Group>
          <ProFormText name="freetime" width="md" label="免费时长" placeholder="请输入免费时长" />
        </Card>
        <Card className={styles.Card} title="充电线计费方式">
          <ProForm.Group title="套餐模式">
            <ProFormDigit
              label="1小时"
              name="pl_mode_1"
              min={0}
              max={20}
              fieldProps={{ precision: 0 }}
              placeholder="未启用"
            />
            <ProFormDigit
              label="2小时"
              name="pl_mode_2"
              min={0}
              max={20}
              fieldProps={{ precision: 0 }}
              placeholder="未启用"
            />
            <ProFormDigit
              label="3小时"
              name="pl_mode_3"
              min={0}
              max={20}
              fieldProps={{ precision: 0 }}
              placeholder="未启用"
            />
            <ProFormDigit
              label="4小时"
              name="pl_mode_4"
              min={0}
              max={20}
              fieldProps={{ precision: 0 }}
              placeholder="未启用"
            />
            <ProFormDigit
              label="5小时"
              name="pl_mode_5"
              min={0}
              max={20}
              fieldProps={{ precision: 0 }}
              placeholder="未启用"
            />
            <ProFormDigit
              label="6小时"
              name="pl_mode_6"
              min={0}
              max={20}
              fieldProps={{ precision: 0 }}
              placeholder="未启用"
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormDigit
              label="7小时"
              name="pl_mode_7"
              min={0}
              max={20}
              fieldProps={{ precision: 0 }}
              placeholder="未启用"
            />
            <ProFormDigit
              label="8小时"
              name="pl_mode_8"
              min={0}
              max={20}
              fieldProps={{ precision: 0 }}
              placeholder="未启用"
            />
            <ProFormDigit
              label="9小时"
              name="pl_mode_9"
              min={0}
              max={20}
              fieldProps={{ precision: 0 }}
              placeholder="未启用"
            />
            <ProFormDigit
              label="10小时"
              name="pl_mode_10"
              min={0}
              max={20}
              fieldProps={{ precision: 0 }}
              placeholder="未启用"
            />
            <ProFormDigit
              label="11小时"
              name="pl_mode_11"
              min={0}
              max={20}
              fieldProps={{ precision: 0 }}
              placeholder="未启用"
            />
            <ProFormDigit
              label="12小时"
              name="pl_mode_12"
              min={0}
              max={20}
              fieldProps={{ precision: 0 }}
              placeholder="未启用"
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormDigit
              label="24小时"
              name="pl_mode_13"
              min={0}
              fieldProps={{ precision: 0 }}
              placeholder="未启用"
            />
          </ProForm.Group>
          <ProForm.Group title="免押计费规则">
            <ProFormText
              name="wired_deposit"
              width="xl"
              label="封顶"
              placeholder="请输入封顶"
              fieldProps={{
                addonAfter: '¥',
              }}
              rules={[{ required: true }]}
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormText
              name="wired_pay_score_start_unit"
              width="sm"
              placeholder="请输入计费时间"
              fieldProps={{
                addonBefore: '规则1: 开始前',
              }}
              rules={[{ required: true }]}
            />
            <ProFormSelect
              name="wired_pay_score_start_type"
              width="sm"
              valueEnum={{
                1: '小时',
                2: '分钟',
              }}
            />
            <ProFormText
              name="wired_pay_score_start_amount"
              width="sm"
              placeholder="请输入费用"
              fieldProps={{
                addonBefore: '收费',
                addonAfter: '¥',
              }}
              rules={[{ required: true }]}
            />
          </ProForm.Group>
          <ProForm.Group>
            <ProFormText
              name="wired_pay_score_unit"
              width="sm"
              placeholder="请输入计费时间"
              fieldProps={{
                addonBefore: '规则2: 之后每',
              }}
              rules={[{ required: true }]}
            />
            <ProFormSelect
              name="wired_pay_score_type"
              width="sm"
              valueEnum={{
                1: '小时',
                2: '分钟',
              }}
            />
            <ProFormText
              name="wired_pay_score_amount"
              width="sm"
              placeholder="请输入费用"
              fieldProps={{
                addonBefore: '收费',
                addonAfter: '¥',
              }}
              rules={[{ required: true }]}
            />
          </ProForm.Group>
        </Card>
      </Spin>
    </ModalForm>
  );
};

export default connect(({ user }: ConnectState) => ({ userState: user.currentUser }))(UpdateFrom);
